package hikari.utils;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TemplateEngine {

    /**
     * @param text text to process<br> Example: <b>My birthday {$date}</b>
     * @param pairKeyValues array of key/values<br> example:<br> new
     * String[][]{<br> {"date",birthday.toString()}<br>
     * @return
     */
    public static String process(String text, String[][] pairKeyValues) {
        return process(text, pairKeyValues, true);
    }

    public static String process(String text, String[][] pairKeyValues, boolean quote) {
        for (String[] keyValue : pairKeyValues) {
            String quotedKey = keyValue[0];
            if (quote) {
                String key = "{$" + keyValue[0] + "}";
                quotedKey = Pattern.quote(key);
            }
            String value = keyValue[1];
            text = replaceAll(text, quotedKey, value);
        }
        return text;
    }

    private static String replaceAll(String text, String pattern, String toReplase) {
        Pattern p = Pattern.compile(pattern, Pattern.DOTALL);
        return p.matcher(text).replaceAll(toReplase);
    }

    public static String showSections(String text, String[] sectionsToShow) {
        for (String sec : sectionsToShow) {
            String startTag = Pattern.quote("{$$") + sec + Pattern.quote("$$}");
            String endTag = Pattern.quote("{/$$") + sec + Pattern.quote("$$}");
            text = process(text, new String[][]{
                        {startTag, ""}, {endTag, ""}}, false);
        }
        String withHiddenSections = hideAllSections(text);
        return withHiddenSections;
    }

    public static String hideAllSections(String text) {
        Pattern pattern = Pattern.compile(Pattern.quote("{$$") + "(.*?)" + Pattern.quote("$$}"));
        Matcher matcher = pattern.matcher(text);
        ArrayList<String> sections = new ArrayList<>();
        while (matcher.find()) {
            int groupCount = matcher.groupCount();
            if (groupCount != 0) {
                String section = matcher.group(1);
                sections.add(section);
            }
        }
        String resultString = text;
        for (String section : sections) {
            String startTag = Pattern.quote("{$$") + section + Pattern.quote("$$}");
            String endTag = Pattern.quote("{/$$") + section + Pattern.quote("$$}");
            String patternText = startTag + ".*" + endTag;
            resultString = replaceAll(resultString, patternText, "");
        }
        return resultString;
    }
}
